import ldap
from django.conf import settings

from utils.custom_log   import log_start
logger = log_start('ldap')


class Ladp_Tools(object):
    def __init__(self):
        
        self.ldap_server_uri = settings.AUTH_LDAP_SERVER_URI
        self.base_dn = settings.BASE_DN
        self.user = settings.AUTH_LDAP_BIND_DN 
        self.password = settings.AUTH_LDAP_BIND_PASSWORD

        try:
            ldap.set_option(ldap.OPT_PROTOCOL_VERSION, ldap.VERSION3)
            self.ldapconn = ldap.initialize(self.ldap_server_uri)
            self.ldapconn.simple_bind_s(self.user,self.password)
        except ldap.LDAPError as e:
            logger.error(e)
        except ldap.INVALID_CREDENTIALS as e:
            logger.error (str(e))


    def ldap_get_vaild(self,uid=None,passwd=None):
        target_cn = self.ldap_search_dn(uid)
        try:
            logger.info('target_cn: %s' % target_cn)
            self.ldapconn.simple_bind_s(target_cn,passwd)
        except ldap.INVALID_CREDENTIALS as e:
            logger.warn('ldap_get_vaild user: %s %s' % (uid,e))
        except Exception as e:
            logger.error('ldap_get_vaild user: %s %s' % (uid,e))
        else:
            logger.info('user:%s check vaild success' % uid)
            return True
        return False

    def ldap_search_dn(self,uid=None):
        searchScope = ldap.SCOPE_SUBTREE
        retrieveAttributes = None
        searchFilter = "uid=" + uid
        try:
            self.ldapconn.simple_bind_s(self.user,self.password)
            logger.info('LDAP connect success!')
            ldap_result_id = self.ldapconn.search(self.base_dn, searchScope, searchFilter, retrieveAttributes)
            result_type, result_data = self.ldapconn.result(ldap_result_id, 0)

            if result_type == ldap.RES_SEARCH_ENTRY:
                #dn = result[0][0]
                return result_data[0][0]
        except ldap.LDAPError as e:
            logger.warn('ldap_search_dn user: %s %s' % (uid,e))
        except Exception as e:
            logger.error('ldap_get_vaild user: %s %s' % (uid,e))


    #查询用户记录，返回需要的信息
    def ldap_get_user(self,uid=None):
        searchScope = ldap.SCOPE_SUBTREE
        retrieveAttributes = None
        searchFilter = "uid=" + uid
        try:
            ldap_result_id = self.ldapconn.search(self.base_dn, searchScope, searchFilter, retrieveAttributes)
            result_type, result_data = self.ldapconn.result(ldap_result_id, 0)
            if result_type == ldap.RES_SEARCH_ENTRY:
                logger.info('get user [%s] info success:[%s]' % (uid,result_data))
                return result_data
            else:
                return None
        except ldap.LDAPError as e:
            logger.warn('ldap_get_user user: %s %s' % (uid,e))
        except Exception as e:
            logger.error('ldap_get_vaild user: %s %s' % (uid,e))


    # 修改用户密码
    def ldap_update_pass(self,uid=None,oldpass=None,newpass=None):
        #modify_entry = [(ldap.MOD_REPLACE,'userpassword',newpass)]
        target_cn = self.ldap_search_dn(uid)
        logger.info("ldap_update_pass" )
        try:
            self.ldapconn.passwd_s(target_cn,oldpass,newpass)
            logger.info('user: %s modify passwd success' % uid )
            return True
        except ldap.LDAPError as e:
            logger.warn('user: %s %s' % (uid,e))
            return False
        except Exception as e:
            logger.error('ldap_update_pass: %s %s' % (uid,e))